/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package estg.dae.projecto.broker.utils;

import estg.dae.projecto.bank.controllers.IBankControllerRemote;
import estg.dae.projecto.broker.controllers.BrokerSessionLocal;
import estg.dae.projecto.broker.model.Bank;
import java.util.Properties;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 *
 * @author Marco
 */
@Stateless
public class BankServiceLocator implements BankServiceLocatorLocal {
    @EJB
    private BrokerSessionLocal controller;

    public IBankControllerRemote getBankService(String bankCode) throws Exception {
        if (!controller.existsBank(bankCode))
            throw new Exception("O banco não se encontra registado");

        Bank bank = controller.getBank(bankCode);
        if (!bank.isActive())
            throw new Exception("O banco não se encontra registado");
        
        try {
            return (IBankControllerRemote) remoteLookup(bank.getHostName()
                    , bank.getHostPort()
                    , IBankControllerRemote.class.getName());
        } catch (NamingException error) {
            error.printStackTrace();
            return null;
        }
    }

    private Object remoteLookup(String host, int port, String jndiName) throws Exception {

        InitialContext context = null;

        Properties props = new Properties();
        props.setProperty(Context.INITIAL_CONTEXT_FACTORY,
                "com.sun.enterprise.naming.SerialInitContextFactory");
        props.setProperty(Context.STATE_FACTORIES,
                "java.naming.factory.state");
        props.setProperty(Context.URL_PKG_PREFIXES,
                "com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl");
        props.setProperty("org.omg.CORBA.ORBInitialHost",
                host);
        props.setProperty("org.omg.CORBA.ORBInitialPort",
                Integer.toString(port));

        try {

            context = new InitialContext(props);
            return context.lookup(jndiName);

        } catch (NamingException ne) {
            throw new Exception("JNDI Service not found at location: " + host + ":" + port);
        }

    }
}
